package nc.bs.sj.dataservlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nc.bs.dao.BaseDAO;
import nc.bs.framework.adaptor.IHttpServletAdaptor;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.bs.uap.lock.PKLock;
import nc.itf.bd.bankacc.cust.ICustBankaccService;
import nc.itf.bd.cust.baseinfo.ICustBaseInfoService;
import nc.itf.uap.IUAPQueryBS;
import nc.itf.uap.pf.IplatFormEntry;
import nc.itf.uif.pub.IUifService;
import nc.jdbc.framework.processor.BeanProcessor;
import nc.jdbc.framework.processor.MapListProcessor;
import nc.md.persist.framework.IMDPersistenceQueryService;
import nc.pub.uapbd.util.FileKit;
import nc.pub.uapbd.util.HttpUtil;
import nc.pub.uapbd.util.ToolHelper;

import nc.vo.ic.general.define.ICBillBodyVO;
import nc.vo.ic.m45.entity.PurchaseInBodyVO;
import nc.vo.ic.m45.entity.PurchaseInHeadVO;
import nc.vo.ic.m45.entity.PurchaseInVO;
import nc.vo.ic.pub.calc.BusiCalculator;
import nc.vo.pu.m21.entity.OrderHeaderVO;
import nc.vo.pu.m21.entity.OrderItemVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.CircularlyAccessibleValueObject;
import nc.vo.pub.VOStatus;
import nc.vo.pub.lang.UFBoolean;
import nc.vo.pub.lang.UFDate;
import nc.vo.pub.lang.UFDateTime;
import nc.vo.pub.lang.UFDouble;
import nc.vo.scmf.ic.hash.util.SCMFHashVOUtils;
import nc.vo.scmf.ic.mbatchcode.BatchcodeVO;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import nc.itf.org.IOrgConst;

public class ToInPurshDataServlet extends CheckDataRule implements IHttpServletAdaptor  {
	public List<String> log_list = new ArrayList<String>();
	IUifService iUifService = NCLocator.getInstance().lookup(IUifService.class);
	ToolHelper helper = new ToolHelper();
	ICustBankaccService custBankaccinfoService = NCLocator.getInstance().lookup(ICustBankaccService.class);
	IUAPQueryBS iUAPQueryBS = (IUAPQueryBS) NCLocator.getInstance().lookup(IUAPQueryBS.class.getName());
	IMDPersistenceQueryService iMDPersistenceQueryService = NCLocator.getInstance().lookup(IMDPersistenceQueryService.class);


	@Override
	public void doAction(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		ICustBaseInfoService icustbaseinfoservice = NCLocator.getInstance().lookup(ICustBaseInfoService.class);
		JSONObject resultMap= new JSONObject();
		String userId = InvocationInfoProxy.getInstance().getUserId();
		IplatFormEntry iplatFormEntry = NCLocator.getInstance().lookup(IplatFormEntry.class);
		try{
			//获取参数
			String reqParas = HttpUtil.getRequestParams(request);
			//参数验证
			String data=super.checkReqParams(request.getRemoteAddr(),reqParas);
			//下面写同步的业务逻辑
			 JSONArray arr=  JSONArray.parseArray(data); 
			 Map<String, String> configMap = new HashMap<String,String>();
		    
			 Map<String, Map<String, String>> docType2InfoMap = new HashMap<String,Map<String, String>>();
			 
			String sql="select a.cgeneralhid,b.cgeneralbid,crowno from ic_purchasein_h a left join ic_purchasein_b b on a.cgeneralhid=b.cgeneralhid where nvl(a.dr,0)=0 and a.vbillcode='"+arr.getJSONObject(0).getString("vbillcode")+"'";
			BaseDAO dao= new BaseDAO();
			List<Map<String, Object>> list=(List<Map<String, Object>>) dao.executeQuery(sql, new MapListProcessor());
			List<Map<String,Object>> bodyList = new ArrayList<Map<String,Object>>();
			List<Map<String,Object>> dataList = new ArrayList<Map<String,Object>>();
			Map<String,Object> dataMap = new HashMap<String,Object>();
			if(list.size()>0){
				for (int i = 0; i < list.size(); i++) {
					Map<String,Object> bodyMap = new HashMap<String,Object>();
				
					bodyMap.put("bodyid", list.get(i).get("cgeneralbid"));
					bodyMap.put("rowid", list.get(i).get("crowno"));
					bodyList.add(bodyMap);	
				}
				dataMap.put("bodys", bodyList);
				dataMap.put("pk",list.get(0).get("cgeneralhid"));
				dataMap.put("vbillcode", arr.getJSONObject(0).getString("vbillcode"));
		
				dataList.add(dataMap);
				resultMap.put("DATA", dataList);
				resultMap.put("STATUS", "200");
				resultMap.put("MESSAGE", "成功");
				this.messageSend(resultMap.toJSONString(), response);
				return;
			}
			PurchaseInVO purchaseInVO = createPurchaseInVO("insert", arr.getJSONObject(0), configMap, docType2InfoMap);
			Object puRetObj = iplatFormEntry.processAction("WRITE", "45", null, purchaseInVO, null, null);
			PurchaseInVO[] puRetVOs = (PurchaseInVO[]) puRetObj;
//			HashMap<String, Object> infoMap = new HashMap<String, Object>();
			
			
			
			ICBillBodyVO[] childrenVO = puRetVOs[0].getChildrenVO();
			for (int i = 0; i < childrenVO.length; i++) {
				Map<String,Object> bodyMap = new HashMap<String,Object>();
				ICBillBodyVO body = childrenVO[i];
				bodyMap.put("bodyid", body.getPrimaryKey());
				bodyMap.put("rowid", body.getCrowno());
				bodyList.add(bodyMap);	
			}
			dataMap.put("bodys", bodyList);
			dataMap.put("pk", puRetVOs[0].getPrimaryKey());
			dataMap.put("vbillcode", arr.getJSONObject(0).getString("vbillcode"));
	
			dataList.add(dataMap);
			resultMap.put("DATA", dataList);
//
//			
			iplatFormEntry.processAction("SIGN", "45", null, puRetVOs[0], null, null);

			resultMap.put("STATUS", "200");
			resultMap.put("MESSAGE", "成功");
			this.messageSend(resultMap.toJSONString(), response);
			
			
		}catch(Exception e){
			resultMap.put("STATUS", "400");
			resultMap.put("MESSAGE", e.getMessage());
			resultMap.put("DATA", null);
			this.messageSend(resultMap.toJSONString(), response);
			StackTraceElement[] stack=	e.getStackTrace();
			for (int j = 0; j < e.getStackTrace().length; j++) {
				log_list.add(e.getStackTrace()[j].getClassName()+"("+e.getStackTrace()[j].getMethodName()+e.getStackTrace()[j].getLineNumber()+")\\n");
			}	
		}finally{
			FileKit.addTask(log_list, "ToInPurshDataServlet");
		}
		
	}
	
	
//	采购入库
	private PurchaseInVO createPurchaseInVO(String routeType, JSONObject jsonObject, Map<String, String> configMap,
			Map<String, Map<String, String>> docType2InfoMap) throws Exception {
		PurchaseInVO vo = null;
		InvocationInfoProxy proxy = InvocationInfoProxy.getInstance();
		String pkVal = null;
		Map<String, String> docCode2PKMap = null;
		if ("insert".equals(routeType)) {
//			处理表头
			String pk_org = jsonObject.getString("pk_org");
			String dbilldate = jsonObject.getString("dbilldate");
			String ctrantypeid = jsonObject.getString("ctrantypeid");
			String vbillcode = jsonObject.getString("vbillcode");
			String cwarehouseid = jsonObject.getString("cwarehouseid");
			// String freplenishflag = jsonObject.getString("freplenishflag");
			String def1 = jsonObject.getString("def1");
			String cdptvid = jsonObject.getString("cdptvid");
			String ntotalnum = jsonObject.getString("ntotalnum");
			String cvendorid = jsonObject.getString("cvendorid");
			String cpprojectid = jsonObject.getString("cpprojectid");
			String billmaker = jsonObject.getString("billmaker");
			String dmakedate = jsonObject.getString("dmakedate");
			String approver = jsonObject.getString("approver");
			String taudittime = jsonObject.getString("taudittime");

			checkNull(pk_org, "采购入库【库存组织】pk_org");
			checkNull(dbilldate, "采购入库【单据日期】dbilldate");
			checkNull(ctrantypeid, "采购入库【出入库类型】ctrantypeid");
			checkNull(vbillcode, "采购入库【入库单号】vbillcode");
			checkNull(cdptvid, "采购入库【部门】cdptvid");
			checkNull(ntotalnum, "采购入库【总数量】ntotalnum");
			checkNull(cvendorid, "采购入库【供应商】cvendorid");
			checkNull(cpprojectid, "采购入库【项目】cpprojectid");
			checkNull(billmaker, "采购入库【制单人】billmaker");
			checkNull(dmakedate, "采购入库【制单时间】dmakedate");
			checkNull(approver, "采购入库【签字人】approver");
			checkNull(taudittime, "采购入库【签字日期】taudittime");


			PurchaseInHeadVO hvo = new PurchaseInHeadVO();
			hvo.setVbillcode(vbillcode);
			hvo.setDbilldate(new UFDate(dbilldate));
			hvo.setDmakedate(new UFDate(dmakedate));
			
			
//			用户
			String sql = "select cuserid from sm_user where nvl(dr, 0) = 0 and user_code = '"+billmaker+"' ";
			List<Map<String, Object>> maplist = (List<Map<String, Object>>) iUAPQueryBS.executeQuery(sql,
					new MapListProcessor());
			if(maplist!=null && !maplist.isEmpty()){
				hvo.setBillmaker(maplist.get(0).get("cuserid").toString());
				InvocationInfoProxy.getInstance().setUserId(maplist.get(0).get("cuserid").toString());
			}else{
				throw new BusinessException("NC65中没有找到编码为【" + billmaker + "】的用户！");
			}
			
			 sql = "select pk_billtypeid from bd_billtype where nvl(dr, 0) = 0 and pk_billtypecode = '"+ctrantypeid+"' ";
			 maplist = (List<Map<String, Object>>) iUAPQueryBS.executeQuery(sql,
					new MapListProcessor());
			if(maplist!=null && !maplist.isEmpty()){
				hvo.setCtrantypeid(maplist.get(0).get("pk_billtypeid").toString());
			}else{
				throw new BusinessException("NC65中没有找到出入库类型为【" + ctrantypeid + "】的交易类型！");
			}
			
			
//			cbiztype 
			
//			sql =  select  pk_busitype from bd_busitype where   pk_busitype = '1001H91000000061BS2B'
		
			hvo.setCbiztype("1001H91000000061BS2B");
			hvo.setVtrantypecode(ctrantypeid);
			hvo.setVbillcode(vbillcode);
			hvo.setVdef1(def1);
			hvo.setStatus(VOStatus.NEW);
			hvo.setCrececountryid(IOrgConst.DEFAULTCOUNTRYZONE);
			hvo.setCsendcountryid(IOrgConst.DEFAULTCOUNTRYZONE);
			hvo.setFbuysellflag(2);
//			报税国家/地区,业务流程
			hvo.setCtaxcountryid(IOrgConst.DEFAULTCOUNTRYZONE);
			proxy.setBizDateTime(hvo.getDbilldate().getMillis());
			hvo.setPk_group(InvocationInfoProxy.getInstance().getGroupId());

//			组织处理
				String orgSQL = "select pk_org,code,name,pk_vid from org_orgs where nvl(dr, 0) = 0 and isbusinessunit = 'Y' and nvl(islastversion, 'N') = 'Y' and name = '"
						+ pk_org + "' and pk_group = '" + hvo.getPk_group() + "'";
				List<Map<String, Object>> orgMapList = (List<Map<String, Object>>) iUAPQueryBS.executeQuery(orgSQL,
						new MapListProcessor());
				if (orgMapList == null || orgMapList.size() < 1) {
					throw new Exception("【所属业务单元】pk_org在NC65没找到对应值！");
				} else {

					hvo.setPk_org(orgMapList.get(0).get("pk_org").toString());
					hvo.setPk_org_v(orgMapList.get(0).get("pk_vid").toString());
				}
			
		
//			结算财务组织
			hvo.setCfanaceorgvid(hvo.getPk_org_v());
			hvo.setCfanaceorgoid(hvo.getPk_org());
//			应付财务组织,报税国家/地区,业务流程,应付财务组织最新版本
			hvo.setCpayfinorgoid(hvo.getPk_org());
			hvo.setCpayfinorgvid(hvo.getPk_org_v());
			
			
			 sql = "select pk_dept,pk_vid from org_dept_v where nvl(dr, 0) = 0  and pk_org = '"
					+ hvo.getPk_org() + "' and code = '" + cdptvid + "'";
			 
			 maplist = (List<Map<String, Object>>) iUAPQueryBS.executeQuery(sql,
						new MapListProcessor());
			 if (maplist == null || maplist.size() < 1) {
					throw new Exception("【部门】cdptvid在NC65没找到对应值！");
				} else {
					 hvo.setCdptvid(maplist.get(0).get("pk_vid").toString());
					 hvo.setCdptid(maplist.get(0).get("pk_dept").toString());
				}
			
			 hvo.setNtotalnum(new UFDouble(ntotalnum));
			 
			 sql = "select pk_supplier from bd_supplier where nvl(dr, 0) = 0 and def2 = '" + cvendorid + "'";
			 maplist = (List<Map<String, Object>>) iUAPQueryBS.executeQuery(sql,
						new MapListProcessor());
			 if (maplist == null || maplist.size() < 1) {
					throw new Exception("【供应商】cvendorid"+cvendorid+"在NC65没找到对应值！");
				} else {
					 hvo.setCvendorid(maplist.get(0).get("pk_supplier").toString());
				}
			 
			 sql = "select pk_project from bd_project where nvl(dr, 0) = 0 and project_code = '" + cpprojectid + "'";
			 maplist = (List<Map<String, Object>>) iUAPQueryBS.executeQuery(sql,
						new MapListProcessor());
			 if (maplist == null || maplist.size() < 1) {
					throw new Exception("【项目】cpprojectid"+cpprojectid+"在NC65没找到对应值！");
			 } else {
				 hvo.setAttributeValue("cpprojectid", maplist.get(0).get("pk_project").toString());
			 }
//			仓库处理
			pkVal = (String) iUifService.findColValue("bd_stordoc", "pk_stordoc", " nvl(dr, 0) = 0 and code = '"
					+ cwarehouseid + "' and pk_org = '" + hvo.getPk_org() + "'");
			if (StringUtils.isBlank(pkVal)) {
				throw new BusinessException("NC65中没有找到名称为【" + cwarehouseid + "】的仓库！");
			}

			
			String pk_taxcode = (String) iUifService.findColValue("bd_taxcode", "pk_taxcode", " nvl(dr, 0) = 0 and code = '13%'");
			if (StringUtils.isBlank(pk_taxcode)) {
				throw new BusinessException("NC65中没有找到名称为【13%】的增值税税码税率！");
			}

			hvo.setCwarehouseid(pkVal);

			vo = new PurchaseInVO();
			vo.setParentVO(hvo);
//			===========================
//			处理表体
			JSONArray bodyArray = jsonObject.getJSONArray("bodyitems");
			PurchaseInBodyVO bvo = null;
			List<PurchaseInBodyVO> bvoList = new ArrayList<>();
			Map<String, OrderItemVO> ke2OrderItemVOMap = new HashMap<String, OrderItemVO>();
			Map<String, OrderHeaderVO> ke2OrderHeaderVOMap = new HashMap<String, OrderHeaderVO>();
			for (int j = 0, blen = bodyArray.size(); j < blen; j++) {
				JSONObject rowObject = bodyArray.getJSONObject(j);
				String crowno = rowObject.getString("crowno");
				String cunitid = rowObject.getString("cunitid");// 主单位
				String cprojectid = rowObject.getString("cprojectid");// 项目
				String cmaterialvid = rowObject.getString("cmaterialvid");// 物料编码
				String vbatchcode = rowObject.getString("vbatchcode");// 批次号
				String nnum = rowObject.getString("nnum");// 实收数量
				

//				String ntax = rowObject.getString("ntax");// 税额
//				String norigmny = rowObject.getString("norigmny");// 无税金额
				String norigtaxprice = rowObject.getString("norigtaxprice");// 主含税单价
				String norigtaxmny = rowObject.getString("norigtaxmny");// 价税合计
				String flargess = rowObject.getString("flargess");// 是否赠品
				
//				norigtaxprice	主含税单价	-
//				norigprice	主无税单价	NC自己计算
//				ntax	税额	NC自己计算
//				norigmny	无税金额	NC自己计算
//				norigtaxmny	价税合计	-

				
				


				checkNull(cprojectid, "采购入库【项目】cprojectid");
//				checkNull(crowno, "采购入库【行号】crowno");
				checkNull(cmaterialvid, "采购入库【物料编码】cmaterialvid");
				checkNull(vbatchcode, "采购入库【批次号】vbatchcode");
				checkNull(nnum, "采购入库【实收数量】nnum");
				checkNull(norigtaxprice, "采购入库【主含税单价】norigtaxprice");
//				checkNull(ntax, "采购入库【税额】ntax");
//				checkNull(norigmny, "采购入库【无税金额】norigmny");
				checkNull(norigtaxmny, "采购入库【价税合计】norigtaxmny");
				checkNull(cunitid, "采购入库【主单位】cunitid");
				checkNull(flargess, "采购入库【是否赠品】flargess");

				bvo = new PurchaseInBodyVO();

				bvo.setFtaxtypeflag(1);
				bvo.setBopptaxflag(UFBoolean.FALSE);
				bvo.setCreqstoorgvid(hvo.getPk_org_v());
				bvo.setCreqstoorgoid(hvo.getPk_org());
				bvo.setVchangerate("1/1");
				bvo.setVqtunitrate("1/1");
				bvo.setNchangestdrate(new UFDouble(1.00000000));
//				bvo.setCrowno((j + 1) * 10 + "");
				bvo.setCrowno(crowno);
				bvo.setVbatchcode(vbatchcode);
				
				 sql = "select pk_project from bd_project where nvl(dr, 0) = 0 and project_code = '" + cprojectid + "'";
				 maplist = (List<Map<String, Object>>) iUAPQueryBS.executeQuery(sql,
							new MapListProcessor());
				 if (maplist == null || maplist.size() < 1) {
						throw new Exception("【项目】cpprojectid"+cprojectid+"在NC65没找到对应值！");
				 } else {
					 bvo.setCprojectid(maplist.get(0).get("pk_project").toString());
				 }

					String cmaterialvidSQL = "select pk_material,code,name,pk_source from bd_material where nvl(dr, 0) = 0 and code = '"
							+ cmaterialvid + "'";
					List<Map<String, Object>> cmaterialvidMapList = (List<Map<String, Object>>) iUAPQueryBS
							.executeQuery(cmaterialvidSQL, new MapListProcessor());
					if (cmaterialvidMapList == null || cmaterialvidMapList.size() < 1) {
						throw new Exception("采购入库【物料编码】cmaterialvid在NC65没找到对应值！");
					} else {
						bvo.setCmaterialvid(cmaterialvidMapList.get(0).get("pk_material").toString());
						bvo.setCmaterialoid(cmaterialvidMapList.get(0).get("pk_source").toString());
						String bpk_batchcode = getBatchcodePk(bvo.getCmaterialvid(), bvo.getCmaterialoid(), vbatchcode);
						bvo.setPk_batchcode(bpk_batchcode);
					}
	
				bvo.setCvendorid(hvo.getCvendorid());
				bvo.setCtaxcodeid(pk_taxcode);
				
				
				
				sql = "select pk_measdoc from bd_measdoc where nvl(dr, 0) = 0 and name = '"+ cunitid + "'";
				maplist = (List<Map<String, Object>>) iUAPQueryBS
						.executeQuery(sql, new MapListProcessor());
				if (maplist == null || maplist.size() < 1) {
					throw new Exception("采购入库【主单位】cunitid在NC65没找到对应值！");
				} else {
					String  pk_measdoc = maplist.get(0).get("pk_measdoc").toString();
					bvo.setCunitid(pk_measdoc);
					bvo.setCqtunitid(pk_measdoc);
					bvo.setCastunitid(pk_measdoc);
				}
				
				UFDouble bnnum = new UFDouble(nnum);
				
				bvo.setCcurrencyid("1002Z0100000000001K1");
				bvo.setCorigcurrencyid("1002Z0100000000001K1");
				bvo.setNqtunitnum(bnnum);
//				String norigtaxprice = rowObject.getString("norigtaxprice");// 主含税单价
//				String norigtaxmny = rowObject.getString("norigtaxmny");// 价税合计
				


				UFDouble hundredUFD = new UFDouble(100);
				UFDouble nassistnumUFD = new UFDouble(nnum);
				UFDouble norigtaxmnyUFD = new UFDouble(norigtaxmny);//价税合计
//				UFDouble ntaxrateUFD = orderItemVO.getNtaxrate() == null ? UFDouble.ZERO_DBL
//						: orderItemVO.getNtaxrate();
				UFDouble ntaxrateUFD =UFDouble.ZERO_DBL;
				UFDouble nqtorigpriceUFD = norigtaxmnyUFD.div(nassistnumUFD)
						.div(ntaxrateUFD.div(hundredUFD).add(UFDouble.ONE_DBL));
				UFDouble nqtorigtaxpriceUFD = norigtaxmnyUFD.div(nassistnumUFD);
//				UFDouble norigmnyUFD = norigtaxmnyUFD.div(ntaxrateUFD.div(hundredUFD).add(UFDouble.ONE_DBL));
				UFDouble norigmnyUFD = norigtaxmnyUFD.div(ntaxrateUFD.div(hundredUFD).add(UFDouble.ONE_DBL));
				UFDouble ntaxUFD = norigtaxmnyUFD.sub(norigmnyUFD);
				

				bvo.setNshouldassistnum(nassistnumUFD);
				bvo.setNshouldnum(nassistnumUFD);
				bvo.setNassistnum(nassistnumUFD);
				bvo.setNnum(nassistnumUFD);
				bvo.setNorigtaxmny(norigtaxmnyUFD);
				bvo.setNtaxrate(ntaxrateUFD);
				bvo.setNqtorigprice(nqtorigpriceUFD);
				bvo.setNqtorigtaxprice(nqtorigtaxpriceUFD);
				bvo.setNorigmny(norigmnyUFD);
				bvo.setNtax(ntaxUFD);
				bvo.setNorigtaxprice(new UFDouble(norigtaxprice));
				bvo.setNtaxrate(new UFDouble(13));
				
				if (vo.getHead().getFreplenishflag() == null) {
					if (nassistnumUFD.compareTo(UFDouble.ZERO_DBL) >= 0) {
						vo.getHead().setFreplenishflag(UFBoolean.FALSE);
					} else {
						vo.getHead().setFreplenishflag(UFBoolean.TRUE);
					}
				}
				if("Y".equals(flargess)){
					bvo.setFlargess(UFBoolean.TRUE);
				}else {
					bvo.setFlargess(UFBoolean.FALSE);
				}

				// 价税合计norigtaxmny为0，自动勾选
//				if (bvo.getFlargess() == null) {
//					if (norigtaxmnyUFD.compareTo(UFDouble.ZERO_DBL) == 0) {
//						bvo.setFlargess(UFBoolean.TRUE);(UFBoolean.TRUE);
//					} else {
//						bvo.setFlargess(UFBoolean.FALSE);
//					}
//				}

				bvoList.add(bvo);
			}
			vo.setChildrenVO(bvoList.toArray(new PurchaseInBodyVO[0]));
		}
		BusiCalculator cal = BusiCalculator.getBusiCalculatorAtBS();

		CircularlyAccessibleValueObject[] allChildrenVO = vo.getAllChildrenVO();

		cal.calcMny(vo.getAllChildrenVO(), "nqtorigprice");
//		cal.calcMny(vo.getAllChildrenVO(), "norigprice");


		return vo;
	}
	
	private String getBatchcodePk(String pk_material,String pk_source,String vbatchcode) throws Exception {
		String pk = "";
			if(vbatchcode!=null&&vbatchcode!="") {
				BatchcodeVO vo = new BatchcodeVO();
				HashMap<String, Object> infoByFieldView = helper.getInfoByFieldView("scm_batchcode", "vbatchcode", vbatchcode,"cmaterialoid",pk_material);
				if(infoByFieldView== null || infoByFieldView.isEmpty()) {
					BatchcodeVO newBatchcodeVO = getNewBatchcodeVO(pk_material,pk_source, vbatchcode);
					pk =  newBatchcodeVO.getPrimaryKey();
				}else {
					pk= infoByFieldView.get("pk_batchcode").toString();
				}

				
			}
			return pk;		 

	}
	
	private  BatchcodeVO getNewBatchcodeVO(String pk_material,String pk_source,String vbatchcode) {
		  BaseDAO dao= new BaseDAO();

		 BatchcodeVO btcvo= new BatchcodeVO();
		 btcvo.setCmaterialoid(pk_material);
		 btcvo.setCmaterialvid(pk_source);
		 btcvo.setVersion(1);
		 btcvo.setVbatchcode(vbatchcode);
		 btcvo.setPk_group("0001A11000000000037Y");
		 btcvo.setAttributeValue("dr", 0);
		 btcvo.setVhashcode(SCMFHashVOUtils.hashCodeContent(btcvo));
		 try {
			String pk= dao.insertVO(btcvo) ;
			btcvo.setPrimaryKey(pk);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 
		 return btcvo;

	}

	
	private boolean isNull(Object obj) {
		if (obj == null || "".equals(obj.toString().trim())|| "null".equals(obj.toString().trim())) {
			return true;
		}
		return false;
	}
	
	
	private void checkNull(String value, String msg) throws BusinessException {
		if (StringUtils.isBlank(value)) {
			throw new BusinessException(msg + "不能为空！");
		}
	}


	/**
	 * 返回信息
	 *
	 * @param msgs
	 * @param response
	 * @return
	 * @throws IOException
	 */
	private Object messageSend(String msgs, HttpServletResponse response) throws IOException {
		response.setCharacterEncoding("UTF-8");
		response.setHeader("contentType", "application/json; charset=utf-8");
		response.setContentType("application/json; charset=utf-8");
		response.getWriter().println(msgs);
		return null;
	}
}
